import * as shop from '@/api/shop'

const state = {
  all: []
}

const mutations = {
  // 修改 state数据
  setProducts (state, payload) {
    state.all = payload.products
  },

  // 添加到购物车，此时产品输量-1
  decrementProductInventoty (state, payload) {
    // console.log(payload)
    const item = state.all.find(({ id }) => id === payload.id)
    item.inventory--
  }

}

const actions = {
  async getAllProducts ({ commit }) {
    // 获取 api 数据（异步）
    const products = await shop.getAllProducts()
    // 提交 mutations
    commit({
      type: 'setProducts',
      products
    })
  }
}

const getters = {}

export default {
  namespaced: true, // 添加命名空间
  state,
  getters,
  mutations,
  actions
}
